'''The globals are stacked thread-local proxies
'''

from clutch.util import bag

from proxy import StackedThreadLocalProxy, ForwardingProxy

class ContextClass(object):

    @classmethod
    def default(cls):
        o = cls()
        o.in_transaction = False
        o.sa_sessions = set()
        o.validation_errors = {}
        o.G = None
        o.topeviews = bag()
        return o

    def js_requires(self):
        result = set()
        for t in self.topeviews.values():
            for r in t.js_requires():
                result.add(r)
        return result

    def css_requires(self):
        result = set()
        for t in self.topeviews.values():
            for r in t.css_requires():
                result.add(r)
        return result

    def dojo_requires(self):
        result = set()
        for t in self.topeviews.values():
            for r in t.dojo_requires():
                result.add(r)
        return sorted(list(result))

    def dojo_onload(self):
        result = []
        for t in self.topeviews.values():
            for r in t.dojo_onload():
                result.append(r)
        return result

    def __repr__(self):
        def _():
            for k,v in self.__dict__.iteritems():
                if k.startswith('_'): continue
                yield '%s=%s' % (k,v)
        attrs = '\n'.join(_())
        return '<ContextClass \n    %s>' % attrs.replace('\n', '\n    ')

C = StackedThreadLocalProxy(factory=ContextClass,
                            initial_factory=ContextClass.default)
G = ForwardingProxy(C, 'G')
